<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <uni-nav-bar 
      title="余额记录" 
      left-icon="back" 
      :right-text="'筛选'"
      @clickLeft="handleBack"
      @clickRight="showFilterModal"
      background-color="#2979FF"
      color="#fff"
    />

    <!-- 统计概览卡片 -->
    <uni-card title="统计概览" :is-shadow="true" margin="15px">
      <view class="stats-overview">
        <view class="stat-item income">
          <view class="stat-icon">
            <uni-icons type="plus-filled" size="20" color="#52c41a" />
          </view>
          <view class="stat-content">
            <text class="stat-value">+¥{{ (statistics.totalIncome / 100).toFixed(2) }}</text>
            <text class="stat-label">总收入</text>
          </view>
        </view>
        
        <view class="stat-item expense">
          <view class="stat-icon">
            <uni-icons type="minus-filled" size="20" color="#f5222d" />
          </view>
          <view class="stat-content">
            <text class="stat-value">-¥{{ (Math.abs(statistics.totalExpense) / 100).toFixed(2) }}</text>
            <text class="stat-label">总支出</text>
          </view>
        </view>
        
        <view class="stat-item net">
          <view class="stat-icon">
            <uni-icons type="wallet" size="20" color="#2979FF" />
          </view>
          <view class="stat-content">
            <text class="stat-value">{{ statistics.recordCount }}次</text>
            <text class="stat-label">变动次数</text>
          </view>
        </view>
      </view>
    </uni-card>

    <!-- 筛选工具栏 -->
    <view class="filter-toolbar">
      <scroll-view scroll-x class="filter-scroll">
        <view class="filter-tags">
          <view 
            class="filter-tag"
            :class="{ active: currentTimeFilter === 'today' }"
            @click="handleTimeFilter('today')"
          >
            今日
          </view>
          <view 
            class="filter-tag"
            :class="{ active: currentTimeFilter === 'week' }"
            @click="handleTimeFilter('week')"
          >
            本周
          </view>
          <view 
            class="filter-tag"
            :class="{ active: currentTimeFilter === 'month' }"
            @click="handleTimeFilter('month')"
          >
            本月
          </view>
          <view 
            class="filter-tag"
            :class="{ active: currentTimeFilter === 'custom' }"
            @click="handleTimeFilter('custom')"
          >
            自定义
          </view>
          <view 
            class="filter-tag"
            :class="{ active: currentTypeFilter !== 'all' }"
            @click="showTypeFilter"
          >
            {{ getTypeFilterText() }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 余额记录列表 -->
    <scroll-view
      scroll-y
      class="record-list-scroll"
      @refresherrefresh="handleRefresh"
      :refresher-triggered="isRefreshing"
      refresher-enabled
      @scrolltolower="handleLoadMore"
    >
      <view v-if="recordList.length > 0" class="record-list">
        <view
          class="record-item"
          v-for="record in recordList"
          :key="record.id"
          @click="showRecordDetail(record)"
        >
          <view class="record-left">
            <view class="record-icon" :class="getRecordTypeClass(record.type)">
              <uni-icons :type="getRecordTypeIcon(record.type)" size="16" color="#fff" />
            </view>
            <view class="record-info">
              <text class="record-type">{{ getRecordTypeName(record.type) }}</text>
              <text class="record-time">{{ formatDateTime(record.created_at) }}</text>
              <text v-if="record.description" class="record-desc">{{ record.description }}</text>
            </view>
          </view>
          
          <view class="record-right">
            <text class="record-amount" :class="{ positive: record.amount > 0, negative: record.amount < 0 }">
              {{ record.amount > 0 ? '+' : '' }}¥{{ (record.amount / 100).toFixed(2) }}
            </text>
            <text class="record-balance">余额: ¥{{ (record.after_balance / 100).toFixed(2) }}</text>
          </view>
        </view>
      </view>
      
      <uni-load-more v-if="recordList.length > 0 || loading" :status="loadingStatus"></uni-load-more>
      
      <view v-if="recordList.length === 0 && !loading" class="empty-container">
        <uni-icons type="wallet" size="60" color="#999"></uni-icons>
        <text class="empty-text">暂无余额记录</text>
      </view>
    </scroll-view>

    <!-- 筛选弹窗 -->
    <uni-popup ref="filterPopupRef" type="bottom">
      <view class="filter-popup">
        <view class="popup-header">
          <text class="popup-title">筛选条件</text>
          <uni-icons type="close" size="20" @click="closeFilterModal" />
        </view>
        
        <view class="filter-content">
          <view class="filter-section">
            <text class="section-title">时间范围</text>
            <uni-datetime-picker 
              v-model="filterForm.startDate"
              type="date"
              :clear-icon="false"
            >
              <template v-slot:default>
                <uni-easyinput 
                  :value="filterForm.startDate" 
                  placeholder="开始日期"
                  readonly
                />
              </template>
            </uni-datetime-picker>
            <uni-datetime-picker 
              v-model="filterForm.endDate"
              type="date"
              :clear-icon="false"
            >
              <template v-slot:default>
                <uni-easyinput 
                  :value="filterForm.endDate" 
                  placeholder="结束日期"
                  readonly
                />
              </template>
            </uni-datetime-picker>
          </view>
          
          <view class="filter-section">
            <text class="section-title">变动类型</text>
            <uni-data-checkbox 
              v-model="filterForm.type" 
              :localdata="typeOptions"
              multiple
            />
          </view>
          
          <view class="filter-section">
            <text class="section-title">金额范围</text>
            <view class="amount-range">
              <uni-easyinput 
                v-model="filterForm.minAmount" 
                type="digit" 
                placeholder="最小金额"
              />
              <text class="range-separator">至</text>
              <uni-easyinput 
                v-model="filterForm.maxAmount" 
                type="digit" 
                placeholder="最大金额"
              />
            </view>
          </view>
        </view>
        
        <view class="popup-footer">
          <button class="reset-btn" @click="resetFilter">重置</button>
          <button class="confirm-btn" @click="applyFilter">确定</button>
        </view>
      </view>
    </uni-popup>

    <!-- 记录详情弹窗 -->
    <uni-popup ref="detailPopupRef" type="center">
      <view class="detail-popup" v-if="currentRecord">
        <view class="popup-header">
          <text class="popup-title">记录详情</text>
          <uni-icons type="close" size="20" @click="closeDetailModal" />
        </view>
        
        <view class="detail-content">
          <view class="detail-row">
            <text class="detail-label">变动类型</text>
            <text class="detail-value">{{ getRecordTypeName(currentRecord.type) }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">变动金额</text>
            <text class="detail-value amount" :class="{ positive: currentRecord.amount > 0, negative: currentRecord.amount < 0 }">
              {{ currentRecord.amount > 0 ? '+' : '' }}¥{{ (currentRecord.amount / 100).toFixed(2) }}
            </text>
          </view>
          <view class="detail-row">
            <text class="detail-label">变动前余额</text>
            <text class="detail-value">¥{{ (currentRecord.before_balance / 100).toFixed(2) }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">变动后余额</text>
            <text class="detail-value">¥{{ (currentRecord.after_balance / 100).toFixed(2) }}</text>
          </view>
          <view v-if="currentRecord.order_no" class="detail-row">
            <text class="detail-label">关联订单</text>
            <text class="detail-value">{{ currentRecord.order_no }}</text>
          </view>
          <view v-if="currentRecord.transaction_no" class="detail-row">
            <text class="detail-label">交易流水号</text>
            <text class="detail-value">{{ currentRecord.transaction_no }}</text>
          </view>
          <view v-if="currentRecord.operator" class="detail-row">
            <text class="detail-label">操作人</text>
            <text class="detail-value">{{ currentRecord.operator }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">变动时间</text>
            <text class="detail-value">{{ formatDateTime(currentRecord.created_at) }}</text>
          </view>
          <view v-if="currentRecord.description" class="detail-row">
            <text class="detail-label">变动说明</text>
            <text class="detail-value">{{ currentRecord.description }}</text>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { onLoad, onShow, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
import { fetchMemberBalanceLog } from '@/api/member';
import type { BalanceLog } from '@/types/member';

const memberId = ref<number | null>(null);
const recordList = ref<BalanceLog[]>([]);
const loading = ref(false);
const isRefreshing = ref(false);
const hasMore = ref(true);
const currentTimeFilter = ref('all');
const currentTypeFilter = ref('all');

const filterPopupRef = ref<any>(null);
const detailPopupRef = ref<any>(null);
const currentRecord = ref<BalanceLog | null>(null);

const queryParams = reactive({
  page: 1,
  pageSize: 10,
  startTime: '',
  endTime: '',
  type: '',
  minAmount: '',
  maxAmount: '',
});

const statistics = reactive({
  totalIncome: 0,
  totalExpense: 0,
  recordCount: 0,
});

const filterForm = reactive({
  startDate: '',
  endDate: '',
  type: [] as number[],
  minAmount: '',
  maxAmount: '',
});

// 变动类型选项
const typeOptions = [
  { value: 1, text: '充值' },
  { value: 2, text: '消费' },
  { value: 3, text: '退款' },
  { value: 4, text: '管理员调整' },
];

const loadingStatus = computed(() => {
  if (loading.value) return 'loading';
  return hasMore.value ? 'more' : 'noMore';
});

// 获取余额记录列表
const getBalanceLogList = async (isRefresh = false) => {
  if (loading.value || !memberId.value) return;
  loading.value = true;

  if (isRefresh) {
    queryParams.page = 1;
  }

  try {
    const res = await fetchMemberBalanceLog(memberId.value, queryParams);
    
    if (isRefresh) {
      recordList.value = res.list;
    } else {
      recordList.value = [...recordList.value, ...res.list];
    }
    
    hasMore.value = recordList.value.length < res.total;
    
    // 更新统计数据
    if (isRefresh) {
      updateStatistics(res.list);
    }
    
    queryParams.page++;
  } catch (error: any) {
    uni.showToast({
      title: error.message || '获取余额记录失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    isRefreshing.value = false;
    uni.stopPullDownRefresh();
  }
};

// 更新统计数据
const updateStatistics = (records: BalanceLog[]) => {
  let totalIncome = 0;
  let totalExpense = 0;
  
  records.forEach(record => {
    if (record.amount > 0) {
      totalIncome += record.amount;
    } else {
      totalExpense += record.amount;
    }
  });
  
  statistics.totalIncome = totalIncome;
  statistics.totalExpense = totalExpense;
  statistics.recordCount = records.length;
};

// 获取记录类型名称
const getRecordTypeName = (type: number) => {
  const typeMap: { [key: number]: string } = {
    1: '充值',
    2: '消费',
    3: '退款',
    4: '管理员调整',
  };
  return typeMap[type] || '未知类型';
};

// 获取记录类型图标
const getRecordTypeIcon = (type: number) => {
  const iconMap: { [key: number]: string } = {
    1: 'plus-filled',
    2: 'minus-filled',
    3: 'redo',
    4: 'gear-filled',
  };
  return iconMap[type] || 'help';
};

// 获取记录类型样式类
const getRecordTypeClass = (type: number) => {
  const classMap: { [key: number]: string } = {
    1: 'charge',
    2: 'consume',
    3: 'refund',
    4: 'adjust',
  };
  return classMap[type] || 'default';
};

// 格式化日期时间
const formatDateTime = (timestamp: number) => {
  const date = new Date(timestamp * 1000);
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const recordDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
  
  if (recordDate.getTime() === today.getTime()) {
    return `今天 ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`;
  } else if (recordDate.getTime() === today.getTime() - 24 * 60 * 60 * 1000) {
    return `昨天 ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`;
  } else {
    return date.toLocaleString('zh-CN');
  }
};

// 处理时间筛选
const handleTimeFilter = (filter: string) => {
  currentTimeFilter.value = filter;
  const now = new Date();
  
  switch (filter) {
    case 'today':
      queryParams.startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString().split('T')[0];
      queryParams.endTime = queryParams.startTime;
      break;
    case 'week':
      const weekStart = new Date(now.getTime() - 6 * 24 * 60 * 60 * 1000);
      queryParams.startTime = weekStart.toISOString().split('T')[0];
      queryParams.endTime = now.toISOString().split('T')[0];
      break;
    case 'month':
      queryParams.startTime = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0];
      queryParams.endTime = now.toISOString().split('T')[0];
      break;
    case 'custom':
      showFilterModal();
      return;
    default:
      queryParams.startTime = '';
      queryParams.endTime = '';
  }
  
  getBalanceLogList(true);
};

// 获取类型筛选文本
const getTypeFilterText = () => {
  if (currentTypeFilter.value === 'all') return '全部类型';
  return getRecordTypeName(parseInt(currentTypeFilter.value));
};

// 显示类型筛选
const showTypeFilter = () => {
  const actions = ['全部类型', '充值', '消费', '退款', '管理员调整'];
  uni.showActionSheet({
    itemList: actions,
    success: (res) => {
      if (res.tapIndex === 0) {
        currentTypeFilter.value = 'all';
        queryParams.type = '';
      } else {
        currentTypeFilter.value = res.tapIndex.toString();
        queryParams.type = res.tapIndex.toString();
      }
      getBalanceLogList(true);
    }
  });
};

// 显示筛选弹窗
const showFilterModal = () => {
  filterPopupRef.value?.open();
};

// 关闭筛选弹窗
const closeFilterModal = () => {
  filterPopupRef.value?.close();
};

// 重置筛选
const resetFilter = () => {
  filterForm.startDate = '';
  filterForm.endDate = '';
  filterForm.type = [];
  filterForm.minAmount = '';
  filterForm.maxAmount = '';
};

// 应用筛选
const applyFilter = () => {
  queryParams.startTime = filterForm.startDate;
  queryParams.endTime = filterForm.endDate;
  queryParams.type = filterForm.type.join(',');
  queryParams.minAmount = filterForm.minAmount;
  queryParams.maxAmount = filterForm.maxAmount;
  
  currentTimeFilter.value = 'custom';
  closeFilterModal();
  getBalanceLogList(true);
};

// 显示记录详情
const showRecordDetail = (record: BalanceLog) => {
  currentRecord.value = record;
  detailPopupRef.value?.open();
};

// 关闭记录详情
const closeDetailModal = () => {
  detailPopupRef.value?.close();
};

// 处理返回
const handleBack = () => {
  uni.navigateBack();
};

// 处理刷新
const handleRefresh = () => {
  isRefreshing.value = true;
  getBalanceLogList(true);
};

// 处理加载更多
const handleLoadMore = () => {
  if (hasMore.value && !loading.value) {
    getBalanceLogList();
  }
};

onLoad((options: any) => {
  if (options.memberId) {
    memberId.value = parseInt(options.memberId);
  }
});

onShow(() => {
  if (memberId.value) {
    getBalanceLogList(true);
  }
});

onPullDownRefresh(() => {
  getBalanceLogList(true);
});

onReachBottom(() => {
  handleLoadMore();
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.stats-overview {
  display: flex;
  justify-content: space-between;
  gap: 15px;
  
  .stat-item {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 8px;
    
    .stat-icon {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .stat-content {
      display: flex;
      flex-direction: column;
      gap: 2px;
      
      .stat-value {
        font-size: 14px;
        font-weight: bold;
        color: #333;
      }
      
      .stat-label {
        font-size: 12px;
        color: #999;
      }
    }
    
    &.income .stat-icon {
      background-color: #52c41a;
    }
    
    &.expense .stat-icon {
      background-color: #f5222d;
    }
    
    &.net .stat-icon {
      background-color: #2979FF;
    }
  }
}

.filter-toolbar {
  background-color: #fff;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  
  .filter-scroll {
    white-space: nowrap;
  }
  
  .filter-tags {
    display: flex;
    gap: 10px;
    padding: 0 15px;
    
    .filter-tag {
      padding: 6px 12px;
      background-color: #f5f5f5;
      border-radius: 16px;
      font-size: 12px;
      color: #666;
      white-space: nowrap;
      
      &.active {
        background-color: #2979FF;
        color: #fff;
      }
    }
  }
}

.record-list-scroll {
  flex: 1;
  height: 0;
}

.record-list {
  padding: 0 15px;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.record-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  
  .record-icon {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    
    &.charge {
      background-color: #52c41a;
    }
    
    &.consume {
      background-color: #f5222d;
    }
    
    &.refund {
      background-color: #1890ff;
    }
    
    &.adjust {
      background-color: #722ed1;
    }
  }
  
  .record-info {
    display: flex;
    flex-direction: column;
    gap: 2px;
    
    .record-type {
      font-size: 14px;
      font-weight: 500;
      color: #333;
    }
    
    .record-time {
      font-size: 12px;
      color: #999;
    }
    
    .record-desc {
      font-size: 12px;
      color: #666;
      margin-top: 2px;
    }
  }
}

.record-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 2px;
  
  .record-amount {
    font-size: 16px;
    font-weight: bold;
    
    &.positive {
      color: #52c41a;
    }
    
    &.negative {
      color: #f5222d;
    }
  }
  
  .record-balance {
    font-size: 12px;
    color: #999;
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #999;

  .empty-text {
    margin-top: 10px;
    font-size: 14px;
  }
}

.filter-popup {
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  max-height: 70vh;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    
    .popup-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }
  
  .filter-content {
    padding: 20px;
    max-height: 50vh;
    overflow-y: auto;
    
    .filter-section {
      margin-bottom: 20px;
      
      .section-title {
        display: block;
        font-size: 14px;
        font-weight: 500;
        color: #333;
        margin-bottom: 10px;
      }
      
      .amount-range {
        display: flex;
        align-items: center;
        gap: 10px;
        
        .range-separator {
          font-size: 14px;
          color: #999;
        }
      }
    }
  }
  
  .popup-footer {
    display: flex;
    gap: 15px;
    padding: 20px;
    border-top: 1px solid #f0f0f0;
    
    .reset-btn {
      flex: 1;
      background-color: #f5f5f5;
      color: #666;
      border: none;
      border-radius: 8px;
      height: 44px;
      font-size: 14px;
    }
    
    .confirm-btn {
      flex: 1;
      background-color: #2979FF;
      color: #fff;
      border: none;
      border-radius: 8px;
      height: 44px;
      font-size: 14px;
    }
  }
}

.detail-popup {
  background-color: #fff;
  border-radius: 12px;
  width: 300px;
  max-height: 70vh;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    
    .popup-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }
  
  .detail-content {
    padding: 20px;
    max-height: 50vh;
    overflow-y: auto;
    
    .detail-row {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 15px;
      
      .detail-label {
        font-size: 14px;
        color: #666;
        width: 80px;
        flex-shrink: 0;
      }
      
      .detail-value {
        flex: 1;
        font-size: 14px;
        color: #333;
        text-align: right;
        word-break: break-all;
        
        &.amount {
          font-weight: bold;
          
          &.positive {
            color: #52c41a;
          }
          
          &.negative {
            color: #f5222d;
          }
        }
      }
    }
  }
}
</style>